package com;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class Img extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String processInstanceId = req.getParameter("processInstanceId");
		
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(req.getSession().getServletContext());
		RepositoryService repository = (RepositoryService)context.getBean("repositoryService");
		RuntimeService runtime = (RuntimeService)context.getBean("runtimeService");
		
		ProcessInstance processInstance = runtime.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
		ProcessDefinition processDefinition = repository.createProcessDefinitionQuery().processDefinitionId(processInstance.getProcessDefinitionId()).singleResult();
	
		InputStream in = repository.getResourceAsStream(processDefinition.getDeploymentId(), processDefinition.getDiagramResourceName());
		
		resp.setContentType("image/png");
		ServletOutputStream out = resp.getOutputStream();
		BufferedInputStream bin = new BufferedInputStream(in);
		
		byte[] b = new byte[1024];
		int l = bin.read(b);
		while(l != -1){
			out.write(b);
			l = bin.read(b);
		}
		bin.close();
		in.close();
		out.flush();
		out.close();
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
}
